<template>
  <page-view class="menu">
    <page-header></page-header>
    <!-- 内容 -->
    <div
      class="content-box"
      ref="contentBoxDOM"
      @scroll="contentBoxScroll($event)"
    >
      <div class="header-box">
        <!-- 轮播图，搜索框可以去跳转到搜索页面 -->
        <swipe class="my-swipe" :autoplay="3000" indicator-color="white">
          <swipe-item v-for="(item, index) in bannerImg" :key="index">
            <van-image
              :src="item"
              width="100%"
              height="200"
              fit="cover"
            ></van-image>
          </swipe-item>
        </swipe>
        <!-- 在轮播图上放一个输入框，点击可以跳转到搜索页 -->
        <div class="query-box" @click="$router.push({ name: 'SearchFood' })">
          <input
            type="text"
            class="query-text"
            readonly
            placeholder="请输入菜品名称"
          />
          <button class="query-btn">搜索</button>
        </div>
      </div>

      <!-- 引入FoodItem组件 -->
      <!-- 菜品列表区域 -->
      <pull-refresh v-model="refreshing" @refresh="onRefresh">
      <div class="food-list" v-if="foodList.length > 0">
        
          <list
            v-model:loading="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <food-item
            v-for="(item, index) in foodList"
            :key="index"
            :f_item="item"
          ></food-item>
          </list>
        
        <!-- 在foodItem组件外套一层，引入下拉刷新、列表vant组件 -->
        <!-- v-model绑定的是是否处于加载状态   @refresh表示：下拉刷新的时候触发的事件-->

      </div>
      </pull-refresh>
    </div>
  </page-view>
</template>

<script>
import { getCurrentInstance, onActivated, onMounted, reactive, ref, toRefs } from "vue";
import { Swipe, SwipeItem, Image as VanImage, PullRefresh, List } from "vant";
import FoodItem from "@/components/FoodItem.vue";
import Api from "../utils/api";
export default {
  name: "Menu",
  components: { Swipe, SwipeItem, VanImage, FoodItem, PullRefresh, List },
  setup() {
    const { proxy } = getCurrentInstance();
    console.log(proxy);
    //组件缓存，高度保留；记录滚动的高度
    let contentBoxDOM = ref(null);
    let contentBoxScrollTop = 0;
    function contentBoxScroll(event) {
      //一滚动就在全局中记录这个高度
      contentBoxScrollTop = event.currentTarget.scrollTop;
    }
    onActivated(()=>{
      contentBoxDOM.value.scrollTop = contentBoxScrollTop;
    })
    let bannerImg = reactive([
      require("../assets/image/01.jpg"),
      require("../assets/image/02.jpg"),
      require("../assets/image/03.jpg"),
      require("../assets/image/04.jpg"),
    ]);

    //获取菜品

    //是否显示加载状态
    const loading = ref(false);
    //是否加载完成
    const finished = ref(false);
    //下拉刷新状态
    const refreshing = ref(false)
    
    //食物数据
    const foodData = reactive({
      pageCount: 0,
      pageEnd: 0,
      pageIndex: 1,
      pageStart: 1,
      totalCount: 0,
      foodList: [],
    });
    //定义一个方法去获取食物在mounted挂载的时候调用
    const getFood = async (pageIndex = 1) => {
      //每次获取菜品列表的时候，处于加载状态开启
      loading.value = true;
      //调用Utils下的axios请求菜品列表数据:// Api.foodInfo.getListByPage()
      let results = await Api.foodInfo.getListByPage({
        pageIndex: pageIndex,
      });
      console.log(results);
      //从获取的菜单列表数据手动解构出我们需要的数据
      foodData.pageCount = results.pageCount;
      foodData.pageEnd = results.pageEn;
      //这里需要将字符串转数组
      foodData.pageIndex = +results.pageIndex;
      foodData.pageStart = results.pageStart;
      foodData.totalCount = results.totalCount;

      //为啥要处理图片的网络地址？因为要拼接baseURL
      results.listData.map((item) => {
        item.food_img = proxy.BaseURL + item.food_img;
        return item.food_img;
      });
      foodData.foodList.push(...results.listData);
      //拿到、保存完数据再将加载状态关闭，是否加载完成的值由当前页和总页数比较决定
      loading.value = false;
      finished.value = foodData.pageIndex>=foodData.pageCount;
      //加载完数据就不再处于刷新状态了
      refreshing.value = false;
    }

    //下滚懒加载菜单
    const onLoad = ()=>{
      if(foodData.pageIndex<foodData.pageCount){
        getFood(foodData.pageIndex+1)
      }
    }
    const onRefresh = () => {
      refreshing.value = true;
      loading.value=true
      finished.value = false;//下拉刷新触发后，列表数据重新加载所以懒加载肯定还没加载完
      //清空菜单列表我们选用那种方式（不用foodData.foodList=[]改变地址，而是改变长度）
      foodData.foodList.length = 0;
      getFood();
    };
    onMounted(() => {
      getFood();
    });
    return {
      contentBoxDOM,
      contentBoxScroll,
      bannerImg,
      ...toRefs(foodData),
      refreshing,
      loading,
      finished,
      onRefresh,
      onLoad
    };
  },
};
</script>

<style lang="scss" scoped>
.menu {
  @include flexbox(column);
  .content-box {
    flex: 1;
    overflow: auto;
    margin-bottom: 60px;
    .header-box {
      position: relative;
      .query-box {
        position: absolute;
        top: 10px;
        left: 40px;
        right: 40px;
        display: flex;
        height: 30px;
        border-radius: 30px;
        overflow: hidden;
        .query-text {
          flex: 1;
          border: none;
          box-sizing: border-box;
          padding: 0px 10px;
          outline: none;
          background-color: rgba($color: #ffffff, $alpha: 0.5);
        }
        .query-btn {
          width: 45px;
          font-size: 14px;
          border: none;
          outline: none;
          background-color: rgba($color: #888888, $alpha: 0.5);
          color: white;
        }
      }
    }
  }
}
</style>